package com.community.shop.utils;

import com.alibaba.nacos.common.utils.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * list 分割工具类
 */
public class ListUtils {

    /**
     * 将集合按照splitSize分成多个子集合返回
     * @param sourceList 原集合
     * @param splitSize 子集合长度
     */
    public static<T> List<List<T>> splitList(List<T> sourceList, int splitSize) {
        List<List<T>> splitList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(sourceList) && splitSize > 0) {
            int sourceSize = sourceList.size();
            int size = sourceSize / splitSize;
            int left = sourceSize % splitSize;
            for (int i = 0; i <= size; i++) {
                if (i == size) {
                    if(left !=0){
                        splitList.add(sourceList.subList(i * splitSize, sourceSize));
                    }
                } else {
                    splitList.add(sourceList.subList(i * splitSize, (i + 1) * splitSize));
                }
            }
        }
        return splitList;
    }

}
